package com.xujiang.myblog.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.message.PushAgent;
import com.xujiang.common.ui.CPBaseActivity;
import com.xujiang.myblog.MainActivity;
import com.xujiang.myblog.R;
import com.xujiang.myblog.model.AccessToken;
import com.xujiang.myblog.model.Login;
import com.xujiang.myblog.model.LoginResult;
import com.xujiang.myblog.model.PreferUser;
import com.xujiang.myblog.network.retrofit.MRetrifit;
import com.xujiang.myblog.util.Callback;
import com.xujiang.myblog.util.NetworkUtils;
import com.xujiang.myblog.util.UIUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

public class LaunchActivity extends CPBaseActivity {

    @BindView(R.id.launch_image)
    ImageView launchImage;

    private Timer mTimer;

    private static final String TAG = LaunchActivity.class.getSimpleName();

    //http://www.cnblogs.com/zenfly/archive/2012/02/10/2345196.html
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        checkPermission();  //检查权限

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UIUtils.immersive(getWindow());
        setContentView(R.layout.activity_launch);
        ButterKnife.bind(this);
        checkPermission();
    }

    //权限检查
    private void checkPermission() {
        //RxPermissions.getInstance(this)  0.7.0版
        new RxPermissions(this).request(  //0.9.0 版
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (!aBoolean) {
                            UIUtils.showToast(getApplicationContext(), "App权限不足");
                            finish();
                        } else {
                            Log.i(TAG,"此处调用了launch");
                            launch();
                        }
                    }
                });
    }

    private void launch() {
        /**
         * 开始动画,α值1.0时表示
         *完全不透明和0.0意味着完全透明。
         * @param toAlpha结局动画的alpha值。
         * 两个参数的意义
         * */
        //http://blog.csdn.net/cswhale/article/details/38706877
        //设置透明度渐变动画
        final AlphaAnimation alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
        //设置动画持续时间
        alphaAnimation.setDuration(3000);
        //设置重复次数 此处参数代表 无限期重复动画。
        alphaAnimation.setRepeatCount(Animation.INFINITE);
        //当动画达到最终INFINTE_REPEAT重复计数 *或积极的价值,动画剧本向后(然后再向前)。
        alphaAnimation.setRepeatMode(Animation.REVERSE);
        launchImage.setAnimation(alphaAnimation);
        //开始动画
        alphaAnimation.start();

        if (mTimer != null) {
            mTimer.cancel();
        }
        mTimer = new Timer();
        //定时任务
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if(!PreferUser.get().isLogin()){
                    if(NetworkUtils.isConnected(getApplicationContext())){
                        if(!TextUtils.isEmpty(PreferUser.get().getUserId()) && !TextUtils
                                .isEmpty(PreferUser.get().getPassword())){
                            autoLogin();
                            return;
                        }
                    }
                    UIUtils.startActivity(getActivity(), LoginActivity.class);
                    finish();
                }else{
                    UIUtils.startActivity(getActivity(), MainActivity.class);
                    finish();
                }


            }
        }, 5000);

    }

    @Override
    protected void onDestroy() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        super.onDestroy();
    }


    private void autoLogin() {
        Login login=new Login(this,PreferUser.get().getUserId(), PreferUser.get().getPassword(),PushAgent.getInstance(this).getRegistrationId());
        MRetrifit.get()
                .login(this,login, this.<AccessToken<LoginResult>>bindToLifecycle(),
                        new Callback.EmptyCallback<AccessToken<LoginResult>>() {  //内部已经保存到本地

                            @Override public void onSuccess(AccessToken o) {
                                PreferUser.get().setLogin(true);
                                UIUtils.startActivity(getActivity(), MainActivity.class);
                                finish();
                            }

                            @Override public void onError(Exception e) {
                                UIUtils.startActivity(getActivity(), LoginActivity.class);
                                finish();
                                e.printStackTrace();
                            }
                        });
    }

}
